{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Historical Factor Scenario\n",
    "\n",
    "In a historical factor scenario, the aim is to replicate the market conditions during a significant or\n",
    "topical historical event and estimate the impact on your portfolio today. The first step is to define the time period\n",
    " of the historical event. Then, factor returns across the time period are geometrically aggregated, and these aggregated\n",
    " returns are the factor shocks that will be used to derive the estimated impact on the performance of your portfolio."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 1: Initialize a GsSession\n",
    "\n",
    "The initial step is to import all required modules and initialize a GsSession with your application ID and secret."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from gs_quant.session import GsSession, Environment\n",
    "from gs_quant.markets.scenario import FactorScenario, FactorScenarioType, HistoricalSimulationParameters\n",
    "from gs_quant.entities.entity import ScenarioCalculationMeasure\n",
    "from gs_quant.markets.portfolio_manager import PortfolioManager\n",
    "from gs_quant.entities.entitlements import Entitlements, EntitlementBlock, User\n",
    "import datetime as dt\n",
    "\n",
    "client = None\n",
    "secret = None\n",
    "\n",
    "## External users must fill in their client ID and secret below and comment out the lines below\n",
    "\n",
    "# client = 'ENTER CLIENT ID'\n",
    "# secret = 'ENTER CLIENT SECRET'\n",
    "\n",
    "GsSession.use(Environment.PROD, client_id=client, client_secret=secret)\n",
    "\n",
    "print('GS Session initialized.')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 2: How do I create a historical factor scenario?\n",
    "\n",
    "Similar to factor shock scenarios, we will need to provide:\n",
    "- A name for the scenario\n",
    "- The type of the scenario. In this case, the scenario type is `FactorScenarioType.Factor_Historical_Simulation`\n",
    "- The parameters of the scenario\n",
    "- Scenario entitlements\n",
    "- A description for the scenario\n",
    "\n",
    "The parameters are defined in a `HistoricalSimulationParameters` object and will define the time\n",
    "period of the historical simulation scenario:\n",
    "\n",
    "- Start Date: The start date of the historical event simulation period\n",
    "- End Date: The end date of the historical event simulation period.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "start_date = dt.date(2023, 1, 1)\n",
    "end_date = dt.date(2024, 1, 1)\n",
    "\n",
    "admin_emails = [\"ADMIN EMAILS\"]\n",
    "edit_emails = [\"EDIT EMAILS\"]\n",
    "view_emails = [\"VIEW EMAILS\"]\n",
    "\n",
    "admin_entitlements = EntitlementBlock(users=User.get_many(emails=admin_emails))\n",
    "edit_entitlements = EntitlementBlock(users=User.get_many(emails=edit_emails))\n",
    "view_entitlements = EntitlementBlock(users=User.get_many(emails=view_emails))\n",
    "\n",
    "scenario_entitlements = Entitlements(view=view_entitlements, edit=edit_entitlements, admin=admin_entitlements)\n",
    "\n",
    "date_range_parameters = HistoricalSimulationParameters(start_date=start_date, end_date=end_date)\n",
    "historical_scenario_name = (\n",
    "    f\"Example historical simulation scenario from {start_date.strftime('%Y-%m-%d')} to {end_date.strftime('%Y-%m-%d')}\"\n",
    ")\n",
    "historical_replay_scenario = FactorScenario(\n",
    "    name=historical_scenario_name,\n",
    "    type=FactorScenarioType.Factor_Historical_Simulation,\n",
    "    parameters=date_range_parameters,\n",
    "    description=f\"Sample historical simulation scenario from {start_date.strftime('%Y-%m-%d')} to {end_date.strftime('%Y-%m-%d')}\",\n",
    "    entitlements=scenario_entitlements,\n",
    ")\n",
    "\n",
    "historical_replay_scenario.save()\n",
    "print(historical_replay_scenario)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## FAQs:\n",
    "\n",
    "### How do I get my Scenarios or Scenarios that are shared with me?\n",
    "\n",
    "You can get saved scenarios that you created or that were shared with you:\n",
    "- By its unique Marquee ID\n",
    "- By its name\n",
    "- By applying filters such as `risk_model`, `type` of the scenario, the `shocked_factors`, or whether the shocks are propagated\n",
    "- For a historical simulation scenario, you can filter by a `start_date` and `end_date`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "risk_model_id = \"RISK MODEL ID\"\n",
    "\n",
    "# Get by id\n",
    "scenario_by_id = FactorScenario.get(\"SCENARIO ID\")\n",
    "\n",
    "# Get all my factor Shock scenarios (and those that are shared with me) with risk model AXIOMA_AXWW4M and whose\n",
    "# factor shocks are propagated to all factors\n",
    "many_scenarios = FactorScenario.get_many(\n",
    "    risk_model=risk_model_id, propagated_shocks=True, type=FactorScenarioType.Factor_Shock\n",
    ")\n",
    "# Get all my factor Shock scenarios (and those that are shared with me) with risk model AXIOMA_AXWW4M that shocks the\n",
    "# Value factor\n",
    "many_scenarios = FactorScenario.get_many(\n",
    "    risk_model=risk_model_id, shocked_factors=[\"Value\"], type=FactorScenarioType.Factor_Shock\n",
    ")\n",
    "\n",
    "# Get all my historical simulation scenarios that are within the requested start and end date\n",
    "historical_simulation_scenarios = FactorScenario.get_many(\n",
    "    type=\"Factor Historical Simulation\", start_date=dt.date(2023, 1, 1), end_date=dt.date(2024, 1, 1)\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### How do I get GS pre-scanned scenarios?\n",
    "\n",
    "To get GS pre-scanned scenarios, you can additionally filter by the tag \"GS\". See below for some examples"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Get 3 factor shocks scenarios with risk model AXIOMA_AXWW4M that propagate factor shocks\n",
    "pre_canned_factor_shock_scenarios = FactorScenario.get_many(\n",
    "    risk_model=risk_model_id, propagated_shocks=True, type=FactorScenarioType.Factor_Shock, tags=[\"GS\"], limit=3\n",
    ")\n",
    "print(pre_canned_factor_shock_scenarios)\n",
    "\n",
    "# Get 3 historical simulation that are within selected start and end date\n",
    "pre_canned_historical_simulation_scenarios = FactorScenario.get_many(\n",
    "    type=\"Factor Historical Simulation\",\n",
    "    start_date=dt.date(2010, 1, 1),\n",
    "    end_date=dt.date(2024, 1, 1),\n",
    "    tags=[\"GS\"],\n",
    "    limit=3,\n",
    ")\n",
    "print(pre_canned_historical_simulation_scenarios)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Running Scenario(s) on a Portfolio\n",
    "\n",
    "To see the estimated impact of scenarios on your portfolio, run the `get_factor_scenario_analytics` function in the\n",
    "`PortfolioManager` class, which is the interface for managing your portfolios in Marquee.\n",
    "\n",
    "A scenario calculation request requires the following components:\n",
    "\n",
    "- A date: date on which to run a scenario. We will run the scenario(s) on your portfolio holdings as of this date.\n",
    "- Scenarios: List of scenarios to run. Can either be a list of unique Marquee IDs, or a scenario object itself.\n",
    "- Risk Model: The risk model to run a scenario with.\n",
    "- Measures: Metrics to return, which include:\n",
    "    1. Total portfolio estimated factor PnL\n",
    "    2. Total portfolio PnL by GICS sector & industry\n",
    "    3. Total portfolio PnL by region\n",
    "    4. Total portfolio PnL by the direction (LONG/SHORT) of your portfolio holdings,\n",
    "    5. Estimated performance of each asset in your portfolio."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "portfolio_id = \"PORTFOLIO ID\"\n",
    "pm = PortfolioManager(portfolio_id)\n",
    "\n",
    "scenario_analytics = pm.get_factor_scenario_analytics(\n",
    "    scenarios=[\"SCENARIO ID\"],\n",
    "    date=dt.date(2024, 4, 10),\n",
    "    measures=[\n",
    "        ScenarioCalculationMeasure.SUMMARY,\n",
    "        ScenarioCalculationMeasure.ESTIMATED_FACTOR_PNL,\n",
    "        ScenarioCalculationMeasure.ESTIMATED_PNL_BY_SECTOR,\n",
    "        ScenarioCalculationMeasure.ESTIMATED_PNL_BY_REGION,\n",
    "        ScenarioCalculationMeasure.ESTIMATED_PNL_BY_DIRECTION,\n",
    "        ScenarioCalculationMeasure.ESTIMATED_PNL_BY_ASSET,\n",
    "    ],\n",
    "    risk_model=risk_model_id,\n",
    ")\n",
    "summary = scenario_analytics.get('summary')\n",
    "factor_pnl = scenario_analytics.get('factorPnl')\n",
    "sector_aggregations = scenario_analytics.get('bySectorAggregations')\n",
    "region_aggregations = scenario_analytics.get(\"byRegionAggregations\")\n",
    "by_asset_aggregations = scenario_analytics.get('byAsset')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Run Scenario(s) on a Basket\n",
    "\n",
    "We can also run one or multiple scenarios on an existing equity custom basket and pull scenario analytics data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from gs_quant.markets.baskets import Basket\n",
    "\n",
    "basket_ticker = \"BASKET TICKER\"\n",
    "basket = Basket.get(basket_ticker)\n",
    "\n",
    "basket_scenario_analytics = basket.get_factor_scenario_analytics(\n",
    "    scenarios=[\"YOUR SCENARIOS\"],\n",
    "    date=dt.date(2024, 4, 1),\n",
    "    measures=[\n",
    "        ScenarioCalculationMeasure.SUMMARY,\n",
    "        ScenarioCalculationMeasure.ESTIMATED_FACTOR_PNL,\n",
    "        ScenarioCalculationMeasure.ESTIMATED_PNL_BY_SECTOR,\n",
    "        ScenarioCalculationMeasure.ESTIMATED_PNL_BY_REGION,\n",
    "        ScenarioCalculationMeasure.ESTIMATED_PNL_BY_DIRECTION,\n",
    "        ScenarioCalculationMeasure.ESTIMATED_PNL_BY_ASSET,\n",
    "    ],\n",
    "    risk_model=risk_model_id,\n",
    ")\n",
    "\n",
    "summary = basket_scenario_analytics.get('summary')\n",
    "factor_pnl = basket_scenario_analytics.get('factorPnl')\n",
    "sector_aggregations = basket_scenario_analytics.get('bySectorAggregations')\n",
    "region_aggregations = basket_scenario_analytics.get(\"byRegionAggregations\")\n",
    "by_asset_aggregations = basket_scenario_analytics.get('byAsset')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "tutorial-env",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
